package com.example.demo.socket;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @desc: <br/>
 * @author: Jingbo Hu<br/>
 * @time：2021年01⽉12⽇<br/>
 * @version：v1.0.0<br>
 */
public class SocketServer {

    public static void main(String[] args) {
        try {
            ServerSocket server = new ServerSocket(8000);
            System.out.println("服务器准备就绪～");
            System.out.println("服务器信息：" + server.getInetAddress() + " Port:" + server.getLocalPort());
            while (true) {
                // 得到客户端
                Socket client = server.accept();
                // 客户端构建异步线程
                ClientHandler clientHandler = new ClientHandler(client);
                // 启动线程
                clientHandler.start();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static class ClientHandler extends Thread {
        private Socket socket;
        private boolean flag = true;

        ClientHandler(Socket socket) {
            this.socket = socket;
        }

        @Override
        public void run() {
            System.out.println("新客户端连接：" + socket.getInetAddress() + " Port:" + socket.getPort());
            // 得到打印流，用于数据输出；服务器回送数据使用
            OutputStream socketOutput = null;
            try {
                socketOutput = socket.getOutputStream();
                PrintStream printStream = new PrintStream(socketOutput);
                // 得到输入流，用于接收数据
                BufferedReader socketInput = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                do {
                    // 客户端拿到一条数据
                    String str = socketInput.readLine();
                    if ("bye".equalsIgnoreCase(str)) {
                        flag = false;
                        // 回送
                        printStream.println("bye");
                    } else {
                        // 打印到屏幕。并回送数据长度
                        System.out.println(str);
                        printStream.println("回送：" + str.length());
                    }
                } while (flag);
                socketInput.close();
                socketOutput.close();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                // 连接关闭
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            System.out.println("客户端已退出：" + socket.getInetAddress() + " Port:" + socket.getPort());
        }
    }
}
